<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php 

class MThumbnailBase extends MModel {
    
    public static $_sizes = array(
        "small"  => array("w"=>32, "h"=>32),
        "medium" => array("w"=>64, "h"=>64),
        "large"  => array("w"=>128, "h"=>128),
        "large@2x" => array("w"=>256, "h"=>256),
        "s"      => array("w"=>64, "h"=>64),
        "m"      => array("w"=>128, "h"=>128),
        "l"      => array("w"=>640, "h"=>480),
        "xl"     => array("w"=>1024, "h"=>768)
    );
    
    public static $_support_types = array(
         "gif" => "image/gif",
         "jpeg" => "image/jpeg",
         "jpg" => "image/jpeg",
         "jpe" => "image/jpeg",
         "png" => "image/png",
         "tiff" => "image/tiff",
         "tif" => "image/tif",
    );
    
    
    public static function initMThumbnailBase($uri, $config = NULL) {
        $thumbnailbase         = new MThumbnailBase();
        
        $format = "JPEG";
        $size   = "small";
        if (isset($_REQUEST["format"])) {
            $format = $_REQUEST["format"];
        }
                                if ($format != "JPEG" && $format != "PNG") {
            $format = "JPEG";
        }
                                if (isset($_REQUEST["size"])) {
            $size = $_REQUEST["size"];
        }
        if (empty(self::$_sizes[$size])) {
            $size = "small";
        }
                                $url_manager = new MUrlManager();
        $path = $url_manager->parsePathFromUrl($uri);
        if ($path == false) {
            throw new MException(FXP::t(MConst::PATH_ERROR), MConst::HTTP_CODE_404);
        }
        $parts = array_slice(explode('/', $uri), 3);
        $root  = $parts[0];                                  $path        = "/" . $path;
        $path        = MUtils::convertStandardPath($path);
                                $user   = MUserManager::getInstance()->getCurrentUser();
        $device = MUserManager::getInstance()->getCurrentDevice();
        
        $thumbnailbase->user_id          = $user->user_id;
        $thumbnailbase->user_nick        = $user->user_name;
        $thumbnailbase->user_device_id = $device->device_id;
        $thumbnailbase->size   = $size;
        $thumbnailbase->format = $format;
        $thumbnailbase->path   = MUtils::convertStandardPath($path);
        $thumbnailbase->root   = $root;
        $thumbnailbase->config = $config;
        return $thumbnailbase;
    }
    
    
    public function checkExistThumbnail($file_name,$size) {
        if ($size == 0 || $size > MConst::MAX_IMAGE_SIZE) {
            throw new MException(FXP::t("The image is invalid and cannot be thumbnailed."), MConst::HTTP_CODE_415);
        }
        $pathinfo  = MUtils::pathinfo_utf($file_name);
        $extension = strtolower($pathinfo["extension"]);
                                if (empty(self::$_support_types[$extension])) {
            throw new MException(FXP::t("The file extension doesn't allow thumbnailing."), MConst::HTTP_CODE_404);;
        }
    }
    
    
    public function create() {
                                $file_detail = MFiles::queryFilesByPath("/" . $this->user_id . $this->path);
        if (count($file_detail) == 0) {
            throw new MException(FXP::t(MConst::PATH_ERROR), MConst::HTTP_CODE_404);
        }
        $file_id    = $file_detail[0]["id"];
        $file_name  = $file_detail[0]["file_name"];
        $file_size  = $file_detail[0]["file_size"];
        $version_id = $file_detail[0]["version_id"];
                $this->checkExistThumbnail($file_name, $file_size);
                                $file_version = MFileVersions::queryFileVersionByID($version_id);
        if (count($file_version) == 0) {
            throw new MException(FXP::t(MConst::PATH_ERROR), MConst::HTTP_CODE_404);
        }
                                $signature = $file_version[0]["file_signature"];
        $store_path = DOCUMENT_ROOT_BLOCK . MUtils::getPathBySplitStr($signature);
        if (file_exists($store_path) == false) {
            throw new MException(FXP::t("The file path was not found."), MConst::HTTP_CODE_404);
        }
        $pathinfo = MUtils::pathinfo_utf($file_name);
        $extension = $pathinfo["extension"];
        $tmp_path = DOCUMENT_TEMP . $signature . ".$extension";
        
                                $rszie = self::$_sizes[$this->size];
        $this->width   = $rszie["w"];
        $this->height  = $rszie["h"];
        $this->handler = NULL;
        $this->image   = $tmp_path;
        $this->resize  = true;
                                $thumbnail  = THUMBNAIL_TEMP . MUtils::getPathBySplitStr($signature);
        $thumbnail .= "_{$this->width}_{$this->height}.{$this->format}";
        if (file_exists($thumbnail) == true) {
            $this->image = $thumbnail;
            $this->resize = false;
        } else {
                        if (file_exists(dirname($thumbnail)) == false) {
                if (MUtils::MkDirs(dirname($thumbnail)) == false) {
                    throw new MException(FXP::t("The file path was not found."), MConst::HTTP_CODE_404);
                }
            }
                        if (file_exists(dirname($tmp_path)) == false) {
                if (MUtils::MkDirs(dirname($tmp_path)) == false) {
                    throw new MException(FXP::t("The file path was not found."), MConst::HTTP_CODE_404);
                }
            }
                        if (file_exists($tmp_path) == false) {
                if (copy($store_path, $tmp_path) == false) {
                    throw new MException(FXP::t("The file path was not found."), MConst::HTTP_CODE_404);
                }
            }
            
                                                if ($this->format != $extension) {
                $fm = new Image($tmp_path);
                $format_path = DOCUMENT_TEMP . $signature . ".{$this->format}";
                $fm->save($format_path);
                                                                unlink($tmp_path);
                $this->image = $format_path;
            }
        }
        
                                try {
            $this->handler = new Image($this->image, isset($this->config)?$this->config:NULL);
        } catch (MException $e) {
            FXP::trace("Exception : $e");
            throw new MException(FXP::t("The image is invalid and cannot be thumbnailed."), MConst::HTTP_CODE_415);
        }
                                if ($this->resize == true) {
            $this->handler->resize($this->width, $this->height)->rotate(0)->quality(75)->sharpen(20);
            $chmod        = 0644;
            $keep_actions = true;
            try {
                $this->handler->save($thumbnail, $chmod, $keep_actions);
            } catch (MException $e) {
                FXP::trace("Exception : $e");
                throw new MException(FXP::t("The image is invalid and cannot be thumbnailed."), MConst::HTTP_CODE_415);
            }
            
        }
    }
    
    
    public function render() {
        $this->handler->render();
    }
}
?>